<template>
  <div>
    <el-dialog title="编辑" class="noselect"
               v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}"
               :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
      <div style="margin: 20px;"></div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label=" " prop="dishesName" :rules="[]">
          <el-input placeholder="请输入商品" v-model="modelForm.dishesName" auto-complete="off" :maxlength="5" size="medium" :disabled="true">
            <template slot="prepend">
              <el-tooltip placement="top" content="请输入商品">
                <el-button tabIndex="-1">商品</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="oldPrice" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">原标准价</div>
            <el-input placeholder="请选择原标准价" auto-complete="off" :maxlength="5" size="medium" :disabled="true" v-model="modelForm.oldPrice">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="name" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">变后标准价</div>
            <el-input placeholder="请输入变后标准价" auto-complete="off" :maxlength="5" size="medium"  v-model="modelForm.price" @focus="printNum" @blur="moneyJiaoyan(modelForm,'price')">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="oldPrice" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">原会员价</div>
            <el-input placeholder="请选择原标准价" auto-complete="off" :maxlength="5" size="medium" :disabled="true"  v-model="modelForm.oldVipPrice">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="name" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">变后会员价</div>
            <el-input placeholder="请输入变后标准价" auto-complete="off" :maxlength="5" size="medium"  v-model="modelForm.vipPrice" @focus="printNum" @blur="moneyJiaoyan(modelForm,'vipPrice')" >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="reason" :rules="[{ required: true, message: '请输入变价原因', trigger: 'blur' }]">
          <el-input placeholder="请输入变价原因" v-model="modelForm.reason" auto-complete="off" :maxlength="25" size="medium">
            <template slot="prepend">
              <el-tooltip placement="top" content="请输入变价原因">
                <el-button tabIndex="-1">变价原因</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="effectiveTime" :rules="[{ required: true, message: '请输入生效日期', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend">
            <div class="el-input-group__prepend">生效日期</div>
            <el-date-picker size="medium"
                            v-model="modelForm.effectiveTime"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择生效日期"
                            style="width:100%;"
                            :picker-options="pickerOptions0"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">适用门店</div>
            <el-input placeholder="请选择" auto-complete="off" :maxlength="5" size="medium" v-model="disName">
              <el-button slot="append" icon="el-icon-caret-bottom" @click="isDistricts=!isDistricts"></el-button>
            </el-input>
          </div>
          <div
            style="position: absolute;z-index:999999;background-color: #fff;width:100%;max-height: 30vh;overflow-y: auto;" v-if="isDistricts">
            <div style="text-align:left">
              <el-tree
              id="myPanel"
              :data="treeData"
              show-checkbox
              node-key="value"
              ref="tree"
              :default-checked-keys="checkedKey"
              default-expand-all @check="getTreeValue"
              >
              </el-tree>
            </div>
            <!---->
          </div>
        </el-form-item>
      </el-form>
      <div class="foot-bar-button">
        <el-button :disabled="canSave" type="primary" size="medium" @click="submitForm('modelForm')">
          <span v-if="canSave"><i class="el-icon-loading"></i>提交中</span>
          <span v-else>提交</span>
        </el-button>
        <!--<el-button type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>-->
        <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  //注意路径
  export default {
    props: ['isShow', 'id'],  //参数
    data() {
      return {
        canSave:false,
        isDishes: false,
        addInfo: false,
        isDistricts:false,
        modelForm: {},
        showDialog: false,
        activityId: "",
        isSave: true,
        downCategeryId: [],
        isUpdate: false,
        treeData: [],
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
          }
        },
        menuList: [],
        dishesList: [],
        allDishesList: [],
        letterList: [],
        tableData: [],
        disName:"",
        selectBransh:[],
        checkedKey:[]

      };
    },
    mounted(){
      let _this=this;
      document.addEventListener("click",function(event){
        var sp = document.getElementById("myPanel");
        if(sp){
          if(!sp.contains(event.target)){            //这句是说如果我们点击到了id为myPanel以外的区域
            _this.isDistricts=false;
          }
        }
      })
    },
    watch: {
      isShow: function (newValue, oldValue) {
        this.showDialog = newValue;
        this.canSave=false;
        if (newValue) {
          if (this.id != '') {
            this.activityId = this.id;
            this.isSave = false;
            this.isUpdate = true;
            this.disName='';
            this.$axios.get("dishes/changePrices/" + this.activityId + "/update").then(data => {
              this.modelForm = data.content.changePrice;
              this.menuList = data.content.menuList;
              var tree = data.content.districts;
              this.newLabel(tree);
              this.treeData = tree;
              this.districtId=[];
              var item=[];
              for(let i=0;i<data.content.branchList.length;i++){
                this.selectBransh.push(data.content.branchList[i].branchId);
                item.push({name:data.content.branchList[i].label,id:data.content.branchList[i].branchId,districtId:data.content.branchList[i].districtId})
              }
              this.disName="";
              var ids=[];
              for(let i=0;i<item.length;i++){
                this.disName +=item[i].name+",";
                // ids.push(item[i].districtId);
                ids.push(item[i].id+"_b");
              }
              this.checkedKey=ids;
            });
          }
        }
      }
    },
    created() {
      window.this = this;
    },
    methods: {
      goTableDel(){

      },
      getTreeValue(){
        var branchs=this.$refs.tree.getCheckedNodes();
        this.checkedKey=[];
        this.selectBransh=[];
        this.disName="";
        for(var i=0;i<branchs.length;i++){
          if(branchs[i].iBranch){
            this.selectBransh.push(branchs[i].id);
            this.disName +=branchs[i].name+","
          }
        }
        if(this.selectBransh){
          for(var i=0;i<this.selectBransh.length;i++){
            this.checkedKey.push(this.selectBransh[i]+"_b")
          }
        }

      },
      tableheaderClassName(){
        return "table_header_cell_style";
      },
      printNum(){
        event.currentTarget.select();
      },
      goNext() {
        //点击确定，循环dishesList，得到选中的，push进tableData;
        var item=[];
        for(var i=0;i<this.dishesList.length;i++){
          if(this.dishesList[i].isSelect){
            item.push(this.dishesList[i]);
          }
        }
        console.log(item);
        if(item.length<=0){
          this.$message.error("请选择商品后点击确定");
          return;
        }
        var count=0;
        for(var i=0;i<item.length;i++){
          for(var j=0;j<this.tableData.length;j++){
                  console.log(item[i].spec_id,this.tableData[j].specId)
            if(item[i].dishes_id==this.tableData[j].dishesId && item[i].spec_id==this.tableData[j].specId  ){
               console.log("000000")
              count++;
            }
          }
          if(count>0){
            this.$message.info("此商品已添加");
          }else{
            this.tableData.push({
              dishesName:item[i].dishes_name,
              dishesId:item[i].dishes_id,
              oldPrice:item[i].price,
              price:item[i].price,
              oldVipPrice:item[i].vip_price,
              vipPrice:item[i].vip_price,
              specName:item[i].spec_name,
              specId:item[i].spec_id
            })
          }
        }
        this.isDishes = false;
        this.addInfo = true;
      },
      getChange(index) {
        console.log(index);
        this.dishesList[index].dishes_name = this.dishesList[index].dishes_name + " "

      },
      goDishes(item) {
        this.dishesList = [];
        for (var i = 0; i < this.allDishesList.length; i++) {
          if (item.name == this.allDishesList[i].letter) {
            this.dishesList = this.allDishesList[i].data;
            return;
          }
        }
      },
      goChose() {
        if (this.modelForm.menuId == '' || this.modelForm.menuId == undefined) {
          this.$message.info("请先选择下发商品库");
          return;
        }
        this.isDishes = !this.isDishes;
        this.addInfo =false;

      },
      getAllDishes() {

        this.$axios.get("dishes/dishesMenus/getDishesByMenu?menuId=" + this.modelForm.menuId).then(res => {
          if (res.success) {
            if (res.content.dishesList.length > 0) {
              this.allDishesList = window.pySort(res.content.dishesList);
              console.log(this.allDishesList);
              for (var i = 0; i < this.allDishesList.length; i++) {
                for (var j = 0; j < this.allDishesList[i].data.length; j++) {
                  this.allDishesList[i].data[j].isSelect = false;
                }
              }
              this.dishesList = this.allDishesList[0].data;
              this.letterList = [];
              for (var i = 0; i < this.allDishesList.length; i++) {
                this.letterList.push({name: this.allDishesList[i].letter, isSelect: false});
              }
              if (this.letterList.length > 0) {
                this.letterList[0].isSelect = true;
              }
            }else{
              this.dishesList=[];
              this.allDishesList=[];
              this.letterList=[];
            }
            var tree = res.content.districts;
            this.newLabel(tree);
            this.treeData = tree;
            console.log(this.treeData);

          }

        }, res => {
        })
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            console.log(newList[i].iBranch);
            if(newList[i].iBranch){
              newList[i].value = newList[i].id + "_b";
            }else {
              newList[i].value = newList[i].id + "";
            }
            newList[i].label = newList[i].name;
            if (!newList[i].children || newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                if(newList[i].iBranch){
                  newList[i].children[s].value = newList[i].children[s].id + "_b";
                }else {
                  newList[i].children[s].value = newList[i].children[s].id + "";
                }
                newList[i].children[s].label = newList[i].children[s].name;
                this.newLabel(newList[i].children[s].children);
              }
            }
          }
        }
      },
      goBack() {
        this.router.go(-1);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var data={};
            if(this.selectBransh.length<=0){
              this.$message.error("请选择门店");
              return;
            }
            data.branchs=this.selectBransh;
            console.log(this.selectBransh);

            this.modelForm.effectiveTime=this.moment(this.modelForm.effectiveTime).format("YYYY-MM-DD")
             data.effectiveTime=this.modelForm.effectiveTime;
             delete this.modelForm.effectiveTime
            delete this.modelForm.operateTime
            data.changePrice=this.modelForm;
             if(this.canSave){
               return ;
             }
             this.canSave=true;
            if (this.isSave) {
              // this.$axios.post("dishes/changePrices/create",data,"json").then(data => {
              //   if (data.status == 200) {
              //     this.$message({
              //       message: data.message,
              //       type: 'success'
              //     });
              //     this.$emit('addSuccess');
              //   } else {
              //     this.$message.error(data.message);
              //   }
              // })
            } else {
              this.modelForm._method = "PUT";
              this.$axios.put("dishes/changePrices/" + this.activityId + "/update",data,"json").then(data => {
                this.canSave=false;
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('close');
        this.showDialog = false;
      },
      handleClose(done) {
        this.$emit('close');
        done();
      },
      isNum(item, key) {
        var r = /^\+?[1-9][0-9]*$/;
        if (!r.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      isDouble(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      moneyJiaoyan(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
    }
  }
</script>
<style scoped>
  .dishesItem:hover {
    background-color: #f2f2f2;
    border-bottom: 1px solid #ccc;
  }

  .activity {
    color: #409EFF !important;
  }

  .tableheaderClassName {
    padding: 0px;
    height: 20px !important;
  }

</style>
